package com.jyx.reflect.instances.factory;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jyx.reflect.instances.util.Bean;
import com.jyx.reflect.instances.util.ParseXml;
import com.jyx.reflect.instances.util.Property;


public class ClassPathXmlApplicationContext {
	
	private static Map<String,Object> objectMap = new HashMap<String,Object>();

	public ClassPathXmlApplicationContext(String path){
		load(path);
	}
	
	/**
	 * 加载配置文件
	 * @param path
	 */
	@SuppressWarnings("rawtypes")
	public void load(String path){
		try {
			String classPath = Thread.currentThread().getContextClassLoader().getResource(path).getPath();
			List<Bean> beanList = ParseXml.parse(classPath);
			for (Bean bean : beanList) {
				Class clz = Class.forName(bean.getClassName());
				// new
				Object object = clz.newInstance();
				
				List<Property> propertyList = bean.getPropertyList();
				for (Property property : propertyList) {
					Field field = clz.getDeclaredField(property.getName());
					field.setAccessible(true);
					
					field.set(object, property.getValue());
				}
				
				objectMap.put(bean.getId(), object);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取bean
	 * @param name
	 * @return
	 */
	public Object getBean(String name){
		return objectMap.get(name);
	}
}
